package com.user.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.io.File;
import org.springframework.web.multipart.MultipartFile;

/*此类采用单例设计模式用于获取数据库连接*/
public class DBUtils {

	public static Connection connection;
	public final static String perfix="`";
	public final static String sufix="`";
	public static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat setPattern(String pattern) {
		try {
			simpleDateFormat.applyPattern(pattern);
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return simpleDateFormat;
	}
	public static SimpleDateFormat getSimpleDateFormat() {
		return simpleDateFormat;
	}
	public static String getPattern() {
		return simpleDateFormat.toPattern();
	}
	public static Timestamp geCurrentTimestamp() {
		return new Timestamp(System.currentTimeMillis());
	}
	public static String geCurrentFormatDateTime() {
		return simpleDateFormat.format(geCurrentTimestamp());
	}
/*输出sql语句*/
	public static void saySql(String method,String sql) {
		System.out.println(method+"\r\n   --->"+sql);
	}
	public static String setFile(MultipartFile pic,String basePathname) throws Exception {
		String originalFilename = pic.getOriginalFilename();
		if (pic != null && originalFilename != null&&(!originalFilename.trim().equals(""))&& originalFilename.length() > 0) {
			File newFile = new File(basePathname, originalFilename);
			pic.transferTo(newFile);
			return originalFilename;
		}else {
			throw new Exception();
		}
	}
/*获取数据库连接对象*/
	public static Connection getConnection() {
		if (connection==null) {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/account?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8","root","root");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return connection;
	}
/*释放资源*/
	public static void close(ResultSet resultSet,Statement statement) {
		try {
			resultSet.close();
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void close(Statement statement) {
		try {
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void close(PreparedStatement preparedStatement, ResultSet resultSet) {
		// TODO Auto-generated method stub
		try {
			preparedStatement.close();
			resultSet.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
